package com.imeem.api.xml;

import org.xml.sax.Attributes;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.imeem.api.results.IResultCallback;
import com.imeem.api.results.ResultData;
import com.imeem.api.results.ResultStatus;

/**
 * This is the base class for handling results from invoking the imeem Media 
 * Platform XML APIs. 
 */
public abstract class ResultHandler extends DefaultHandler
{
   protected String _element;
   protected String _currentData;
   protected Object _data;
   
   //private Locator _locator;
   private final IResultCallback _function;
   private final Object _context;
   private ResultStatus _status;
   
   public ResultHandler(IResultCallback function, Object context)
   {
      _function = function;
      _status = new ResultStatus();
      _context = context;
   }
   
   //public abstract Object getData();
   
   public void characters(char[] ch, int start, int length) throws SAXException
   {
      _currentData = null == ch || 0 == length ? null : new String(ch, start, length);

      if (0 == "statusCode".compareTo(_element))
      {
         _status.setStatusCode(Integer.parseInt(_currentData));
      }
      else if (0 == "statusDescription".compareTo(_element))
      {
         _status.setDescription(_currentData);
      }
      else if (0 == "statusDetails".compareTo(_element))
      {
         _status.setDetails(_currentData);
      }
   }

   public void endDocument() throws SAXException
   {
      _function.callback(new ResultData(_status, _data, _context));
   }
   
   public void endElement(String uri, String localName, String qName)
     throws SAXException
   {
      //System.out.println("endElement: " + uri + " " + localName  +" " + qName);
      _element = null;
      _currentData = null;
   }
   
   public void setDocumentLocator(Locator locator)
   {
      //_locator = locator;
   }
   
   
   public void startDocument() throws SAXException
   {

   }
   
   public void startElement(String uri, String localName, String qName, Attributes atts)
     throws SAXException
   {
      // System.out.println("startElement: " + uri + " " + localName + " " + qName);
      _element = localName;
   }
}
